package com.jk.controller.admin;

import com.github.pagehelper.PageInfo;
import com.jk.controller.BaseController;
import com.jk.model.User;
import com.jk.service.UserService;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author cuiP
 *         Created by JK on 2017/1/19.
 */
@Controller
@RequestMapping("/admin/manager")
public class UserController extends BaseController {

    private static final String BASE_PATH = "/admin/manager/";

    @Resource
    private UserService userService;

    /**
     * 分页查询管理员列表
     *
     * @param pageNum   当前页码
     * @param username  用户名
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param modelMap
     * @return
     */
    @GetMapping(value = "/user")
    public String list(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            User model, String username, String startTime, String endTime, ModelMap modelMap) {
        try {
            log.debug("分页查询管理员列表参数! pageNum = {}, username = {}, username = {}, startTime = {}, endTime = {}", pageNum, username, startTime, endTime);
            PageInfo<User> pageInfo = userService.findPage(pageNum, model.getPageSize(), username, startTime, endTime);
            log.info("分页查询管理员列表成功！ pageInfo = {}", pageInfo);
            modelMap.put("pageInfo", pageInfo);
            modelMap.put("username", username);
            modelMap.put("startTime", startTime);
            modelMap.put("endTime", endTime);
        } catch (Exception e) {
            log.error("分页查询管理员列表错误! e = {}", e.getMessage());
        }
        return BASE_PATH + "admin-list";
    }

    /**
     * 根据主键ID删除管理员
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/user/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") Long id) {
        try {
            log.debug("删除管理员! id = {}", id);

            if (null == id) {
                log.info("删除管理员不存在! id = {}", id);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            userService.deleteById(id);
            log.info("删除管理员成功! id = {}", id);

            return ResponseEntity.ok(null);
        } catch (Exception e) {
            log.debug("删除管理员错误! id = {}, e = {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 批量删除管理员
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/user/batch/{ids}")
    public ResponseEntity<Void> deleteBatch(@PathVariable("ids") List<Object> ids) {
        try {
            log.debug("批量删除管理员! ids = {}", ids);

            if (null == ids) {
                log.info("批量删除管理员不存在! ids = {}", ids);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            userService.deleteByIds(User.class, "id", ids);
            log.info("批量删除管理员成功! ids = {}", ids);

            return ResponseEntity.ok(null);
        } catch (Exception e) {
            log.debug("批量删除管理员错误! id = {}, e = {}", ids, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 禁用|启用
     * @param id
     * @return
     */
    @PutMapping(value = "/user/status/{id}")
    public ResponseEntity<Void> updateStatus(@PathVariable("id") Long id){
        try {
            if (null == id) {
                log.info("管理员不存在! id = {}", id);
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }

            User user = userService.findById(id);

            //禁用启用
            user.setLock(!user.getLock());
            userService.updateSelective(user);

            log.info("禁用|启用管理员成功! id = {}", id);
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        } catch (Exception e) {
            log.debug("禁用|启用管理员错误! id = {}, e = {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 跳转到管理员添加页面
     * @return
     */
    @GetMapping(value = "/user/add")
    public String add(){
        return BASE_PATH+"admin-add";
    }

    /**
     * 添加管理员
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping(value = "/user")
    public ModelMap saveUser(User user){
        ModelMap messagesMap = new ModelMap();

        try {
            log.debug("添加管理员参数! user = {}", user);
            //加密
            user.setPassword(SecureUtil.md5().digestHex(user.getPassword()));
            user.setLock(false);
            user.setDel(false);
            userService.save(user);
            log.info("添加管理员成功! user = {}", user);
            messagesMap.put("status",SUCCESS);
            messagesMap.put("message","添加成功!");
            return messagesMap;
        } catch (Exception e) {
            log.error("添加管理错误! user = {}, e = {}", user, e);
            messagesMap.put("status",FAILURE);
            messagesMap.put("message","添加失败!");
            return messagesMap;
        }
    }

    /**
     * 跳转到管理员修改页面
     * @return
     */
    @GetMapping(value = "/user/edit")
    public String edit(){
        return BASE_PATH+"admin-edit";
    }

    /**
     * 更新管理员信息
     * @param id
     * @param user
     * @return
     */
    @PutMapping(value = "/user/{id}")
    public ResponseEntity<Void> saveUser(@PathVariable("id") Long id, User user){
        try {
            log.debug("修改管理员参数! id= {}, user = {}", id, user);
            User record = userService.findById(id);
            if(null == record){
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            userService.updateSelective(user);
            log.info("修改管理员成功! id= {}, user = {}", id, user);
            return ResponseEntity.status(HttpStatus.CREATED).build();
        } catch (Exception e) {
            log.error("修改管理错误! id = {}, user = {}, e = {}", id, user, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
